package com.spring.security.core.annotation;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.annotation.Resource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.spera.genutil.TokenUtil;
import com.spring.security.web.dao.JedisCache;
import com.spring.security.web.model.BaseResult;
import com.spring.tools.MyTools;

@Aspect
@Component
public class SpringCheckToken {
	@Resource private JedisCache jedisCache;

	@Pointcut("@annotation(com.spring.security.core.annotation.CheckToken)")
	public void checkToken(){
	}
	
	@Around("checkToken()")
	public Object aroundExec(ProceedingJoinPoint pjp) throws Throwable{
		Object[] parameters=pjp.getArgs();
		if(parameters.length>0){
			String token;
			if(parameters[0] instanceof String){
				token=MyTools.ObjectToString(parameters[0]);		
			}else{
				token=getObjectToken(parameters[0]);
			}
			BaseResult checkResultBR = TokenUtil.checkTokenBR(token, jedisCache);
		   	if (checkResultBR!=null) {
		   		return checkResultBR;
		   	}	
		}
		return pjp.proceed();
	}
	
	private String getObjectToken(Object obj) throws Exception{
		Method method = obj.getClass().getMethod("getToken");
		String token = MyTools.ObjectToString(method.invoke(obj)); 
		return token;
	}
	
}
